package com.sjz.test2;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/****
 * 日期多线程 安全问题
 *
 */
public class TestSimpleDateFormat {
   public static void main(String[] args) throws Exception {
	   test3();
}
   
    /****
     * 新的jdk的日期类型  解决 多线程安全问题
     * @throws Exception
     */
   public static void test3() throws  Exception{
	   DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
	   ExecutorService pool = Executors.newFixedThreadPool(10);
	   Callable<LocalDate> task = new Callable<LocalDate>() {

			@Override
			public LocalDate call() throws Exception {
				LocalDate ld = LocalDate.parse("20161121", dtf);
				return ld;
			}
			
		};
		List<Future<LocalDate>> results = new ArrayList<>();
		
	   for (int i = 0; i < 10; i++) {
			results.add(pool.submit(task));
		}
	   
	   for (Future<LocalDate> future : results) {
			System.out.println(future.get());
		}
	   
	   pool.shutdown();
   }
   
   /****
    * 以前传统日期的多线程安全处理的方式  使用threadLocal
    * @throws Exception
    */
 public static void test2() throws  Exception {
	   ExecutorService pool = Executors.newFixedThreadPool(10);
	   Callable<Date> task = new Callable<Date>() {

			@Override
			public Date call() throws Exception {
				return DateFormatThreadLocal.convert("20161121");
			}
			
		};
		List<Future<Date>> results = new ArrayList<>();
		
	   for (int i = 0; i < 10; i++) {
			results.add(pool.submit(task));
		}
	   
	   for (Future<Date> future : results) {
			System.out.println(future.get());
		}
	   
	   pool.shutdown();
 }
   
   /***
    * 传统的时间格式的对象  会有多线程问题
    * @throws Exception
    */
   public static void test1() throws  Exception {
	   SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
	   ExecutorService pool = Executors.newFixedThreadPool(10);
	   Callable<Date> task = new Callable<Date>() {

			@Override
			public Date call() throws Exception {
				return sdf.parse("20161121");
			}
			
		};
		List<Future<Date>> results = new ArrayList<>();
		
	   for (int i = 0; i < 10; i++) {
			results.add(pool.submit(task));
		}
	   
	   for (Future<Date> future : results) {
			System.out.println(future.get());
		}
	   
	   pool.shutdown();
   }
}
